import { NextResponse } from 'next/server';
import { getTodos, addTodo, toggleTodo, deleteTodo } from '@/lib/db';
import { Todo } from '@/types/todo';

// 获取所有待办事项
export async function GET() {
  try {
    // 使用默认用户ID 1，与 middleware/auth.ts 中保持一致
    const userId = 1;
    const todos = getTodos(userId);
    return NextResponse.json(todos);
  } catch (error) {
    console.error('Failed to fetch todos:', error);
    return NextResponse.json(
      { error: 'Failed to fetch todos' },
      { status: 500 }
    );
  }
}

// 添加新的待办事项
export async function POST(request: Request) {
  try {
    const { text } = await request.json();
    
    if (!text || typeof text !== 'string' || text.trim() === '') {
      return NextResponse.json(
        { error: 'Todo text is required' },
        { status: 400 }
      );
    }
    
    // 使用默认用户ID 1，与 middleware/auth.ts 中保持一致
    const userId = 1;
    const newTodo = addTodo(text.trim(), userId);
    return NextResponse.json(newTodo, { status: 201 });
  } catch (error) {
    console.error('Failed to add todo:', error);
    return NextResponse.json(
      { error: 'Failed to add todo' },
      { status: 500 }
    );
  }
}

// 更新待办事项状态
export async function PATCH(request: Request) {
  try {
    const { id, completed } = await request.json();
    
    if (id === undefined || completed === undefined) {
      return NextResponse.json(
        { error: 'ID and completed status are required' },
        { status: 400 }
      );
    }
    
    // 确保 id 是数字类型
    const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
    
    if (isNaN(numericId)) {
      return NextResponse.json(
        { error: 'ID must be a valid number' },
        { status: 400 }
      );
    }
    
    const updatedTodo = toggleTodo(numericId, completed);
    
    if (!updatedTodo) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }
    
    return NextResponse.json(updatedTodo);
  } catch (error) {
    console.error('Failed to update todo:', error);
    return NextResponse.json(
      { error: 'Failed to update todo' },
      { status: 500 }
    );
  }
}

// 删除待办事项
export async function DELETE(request: Request) {
  try {
    const { id } = await request.json();
    
    if (id === undefined) {
      return NextResponse.json(
        { error: 'ID is required' },
        { status: 400 }
      );
    }
    
    // 确保 id 是数字类型
    const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
    
    if (isNaN(numericId)) {
      return NextResponse.json(
        { error: 'ID must be a valid number' },
        { status: 400 }
      );
    }
    
    const result = deleteTodo(numericId);
    
    if (!result) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Failed to delete todo:', error);
    return NextResponse.json(
      { error: 'Failed to delete todo' },
      { status: 500 }
    );
  }
}